/**
 *  API初级封装
 */
import store from '@/store'
import {
  getStorageSync
} from "@/libs/util";

//获取API配置
export const appInfo = function() {
  let appInfo = {};
  try {
    let appInfoStr = getStorageSync('appInfo');
    if (appInfoStr) {
      appInfo = JSON.parse(appInfoStr); 
    }
  } catch (e) {
    console.log(e);
  } 
  return appInfo;  
};

//请求
export const request = function(data) {
  console.log("api:"+JSON.stringify(data));
  if (!data.header) {
    data.header = {'content-type': 'application/x-www-form-urlencoded'};
  }
	return new Promise((resolve, reject) => {
		uni.request(data).then((res) => {
			//console.log(res);
			//0是错误，1是返回
			let dataObj = res[1].data;
      if (dataObj.code === 401) {
        //删除缓存
        store.dispatch('handleClientLogOut');
        uni.showToast({
          icon: 'none',
          title: '没有权限,请登录后使用！',
          duration:'3000'
        });
        setTimeout(function() {
          uni.reLaunch({
            url: '/pages/login/login'
          });
        }, 3000);
        reject(data);
      } else {
        resolve(dataObj);
      }
		}).catch((error) => {
			console.log("Request error:", data.url, error);
			reject(error);
		});
	});
};

//上传文件
export const uploadFile = function(obj) {
	uni.chooseImage(obj);
}

//下载文件
export const downloadFile = function(obj) {
	uni.downloadFile(obj);
}